package com.antd.admin.server.strategy.passwd;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.antd.admin.api.dto.ResetPasswdDto;
import com.antd.admin.api.entity.SysUser;
import com.antd.admin.server.service.ISysUserService;
import com.antd.common.auth.util.AntdSecurityUtil;
import com.antd.common.core.constant.AntdConstant;
import com.antd.common.core.exception.BaseException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * TODO
 *
 * @author 子丶沫
 * @version 1.0
 * @date 2020/12/5 16:10
 */
@Slf4j
@Component("resetPasswd"+AntdConstant.RESET_PHONE)
public class ResetPasswdPhoneHandler implements ResetPasswdHandler {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private ISysUserService userService;
    @Override
    public boolean resetPassword(ResetPasswdDto resetPasswdDto) {
        String smsCode = resetPasswdDto.getSmsCode();
        String phone=resetPasswdDto.getPhone();
        if(StrUtil.isBlank(phone)){
            throw new BaseException("手机号码不能为空.");
        }
        if(StrUtil.isBlank(smsCode)){
            throw new BaseException("短信验证码不能为空.");
        }
        String code = redisTemplate.opsForValue().get(AntdConstant.ANTD_SMS_CODE_KEY + phone);
        if(StrUtil.isBlank(code)){
            throw new BaseException("验证码已过期.");
        }
        if(!smsCode.equalsIgnoreCase(code)){
            throw new BaseException("验证码不正确.");
        }
        redisTemplate.delete(AntdConstant.ANTD_SMS_CODE_KEY + phone);
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getPhone, phone));
        if(ObjectUtil.isNull(user)){
            throw new BaseException("未找到与此手机号码相关的用户,请检查您的信息.");
        }
        String password = AntdSecurityUtil.encodePassword(resetPasswdDto.getPassword());
        user.setPassword(password);
        return userService.updateById(user);
    }
}
